package com.jia.config;

import com.jia.pojo.User;
import com.jia.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

// 自定义的Realm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了授权-PrincipalCollection");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 授权
        // info.addStringPermission("user:add");
        // 拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        // 取出user
        User currentUser = (User) subject.getPrincipal();
        // 设置当前用户的权限
        info.addStringPermission(currentUser.getPrems());

        return info;
    }
    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认知-AuthenticationToken");
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        // 用户名 密码，数据库中取
        User user = userService.selectUserByName(userToken.getUsername());
        if (user == null){ // 没有用户
            return null;
        }

        // 密码认知 shiro自己做
        // 密码加密 MD5 加密 MD5盐值加密
        // 传递user 并验证密码
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
